import {host,port} from "../configfile/config.js"
$(function() {
    const baseURL = "http://" + host + ":" + port
    const ping_list = { "weixin": "微信", "weiboAPI": "微博API","weiboScrapy": "微博Scrapy", "baijiahao": "百家号","baidu": "百度" }
    const pingtai = { "微信": "weixin", "微博API": "weiboAPI", "微博Scrapy": "weiboScrapy","百家号": "baijiahao","百度": "baidu" }
    var getdata_list = { "current": 1, "status": "" }
    var r
    var list
    var size = 9; //每页显示九条数据
    var page //总共可以分的页数
    var pageCount = 5 // 页面显示的分页个数
    var Current

    //刷新页面
    function resetUI() {
        r = gettasklist(getdata_list);
        list = r.list
        page = r.page
        Current = r.current
        get_content(list, size, Current);
        get_page(page, Current, pageCount);

    }

    resetUI()

    //定时查询数据库,每隔十秒
    var timer = setInterval(function() {
        resetUI()
    }, 10000);

    // 获取所有的任务列表
    function gettasklist(data) {
        var l;
        let url_current = baseURL + "/gettask"
        let response = {}
        $.ajax({
            type: "GET",
            async: false,
            ContentType: 'application/json',
            data: data,
            url: url_current,
            success: function(res) {
                response.list = res.data
                response.page = res.page
                response.current = res.current
                console.log(res.data);
            }
        })
        return response
    }

    //根据选中的页码显示特定的内容
    function get_content(list) {
        let rows = []
        $(".task_list").empty();
        $(list).each(function(index, item) {
            var li = '<li>\
                        <div class="task_card">\
                            <div class="task_detail">\
                                <ul>\
                                    <li>任务名\uff1a<span>' + item.name + '</span></li>\
                                    <li>关键词\uff1a<span>' + item.kwd + '</span></li>\
                                    <li>来源\uff1a<span>' + item.source + '</span></li>\
                                    <li>开始时间\uff1a<span>' + item.fromdate + '</span></li>\
                                    <li>结束时间\uff1a<span>' + item.todate + '</span></li>\
                                    <li>已完成\uff1a<span>' + item.complete + '</span></li>\
                                    <li>任务周期\uff1a<span>' + item.cycle + '</span></li>\
                                    <li>任务状态\uff1a<span>' + item.status + '</span></li>\
                                </ul>\
                            </div>\
                            <div class="task_operation">\
                                <ul id=' + item.name + '-' + item.source + '>\
                                    <li class="cur scan"></li>\
                                    <li class="cur delete"></li>\
                                    <li class="cur edit"></li>\
                                    <li class="cur bianhua ' + item.status + '"></li>\
                                </ul>\
                            </div>\
                        </div>\
                    </li>'
            rows.push(li)
        })
        $(".task_list").append(rows.join(''));
    }
    //获取当前页码下，分页的显示状态
    function get_page(page, current, pageCount) {
        let rows = []
            // 左按钮
        var li = '<li class="pagenumber" id = "page-prev"></li>'
        rows.push(li)
            // 中间按钮
        if (page === 0) {
            alert("请添加新任务")
        } else if (current < 1 || current > page) {
            throw "页码错误";
        } else if (page <= pageCount) {
            // console.log("第一条判断语句");
            for (var i = 1; i < page + 1; i++) {
                li = '<li class="pagenumber" id = "page-' + i + '">' + i + '</li>'
                rows.push(li)
            }
        } else if (current <= pageCount - 1 && page > pageCount) {
            // console.log("第二条判断语句");
            for (var i = 1; i < pageCount + 1; i++) {
                li = '<li class="pagenumber" id = "page-' + i + '">' + i + '</li>'
                rows.push(li)
            }
        } else if (current > page - pageCount + 1) {
            // console.log("第三条判断语句");
            for (var i = page - pageCount + 1; i < page + 1; i++) {
                li = '<li class="pagenumber" id = "page-' + i + '">' + i + '</li>'
                rows.push(li)
            }
        } else {
            // console.log("第四条判断语句");
            var beforeNumber = current - Math.floor((pageCount - 1) / 2)
            var afterNumber = current + Math.ceil((pageCount - 1) / 2)
            for (var i = beforeNumber; i < afterNumber + 1; i++) {
                li = '<li class="pagenumber" id = "page-' + i + '">' + i + '</li>'
                rows.push(li)
            }

        }
        //右按钮
        li = '<li class="pagenumber" id = "page-next"></li>'
        rows.push(li)
        $(".pagenation").empty().append(rows.join(''));
        $(".pagenation #page-" + Current).addClass("active")
        if (Current == 1) {
            $('#page-prev').removeClass("pagenumber")
        }
        if (Current == page) {
            $('#page-next').removeClass("pagenumber")
        }
    }

    //点击页码
    $(".pagenation").on("click", ".pagenumber", function(e) {
        var id = $(this).attr("id").split("-")[1];
        if (id === "prev") {
            getdata_list.current -= 1;
        } else if (id === "next") {
            getdata_list.current += 1;
        } else {
            $(".pagenumber").each(function(i, item) {
                $(item).removeClass("active")
            })
            getdata_list.current = parseInt(id)
        }
        resetUI();
    })

    //任务名不允许出现-
    $(".canshu-list #name").bind('input propertychange', function() {
        var source = $(this).attr('data-name');
        $('.' + source + ' .add').removeAttr("disabled")
        // console.log($('.' + source + ' #name').val().split(''));
        if ($('.' + source + ' #name').val().split('').indexOf('-') !== -1) {
            $('.' + source + ' .add').attr("disabled", "ture")
            alert("任务名不允许出现'-'符号")
        }
    })


    //取消按钮效果
    function click_cancel() {
        $(".form-horizontal input").each(function(index, value) {
            $(value).val("")
        })
        $(".form-horizontal textarea").val("")
        $(".shade").css("opacity", "0").css("z-index", "0");
        $(".edit_task").css("transform", "scale(0.5)");
        $(".box").css("z-index", "1");
        $(".pingtai-list").css("opacity", "1").css("z-index", "1").css("transform", "scale(1)");;
        $(".canshu-list").css("opacity", "0").css("z-index", "0");
    }



    // 点击任务卡片的开始或是暂停按钮
    $(".task_list").on("click", ".bianhua", function(e) {
        var status = $(this).attr("class").split(" ")[2]
        $(this).removeClass(status)
            // 如果此时任务状态为stop，将任务改为等待运行状态wait；如果任务状态为登台运行wait或者是运行中状态run，一律改为结束状态stop
        if (status == "stop") {
            $(this).addClass("wait")
            status = "wait"
        } else {
            $(this).addClass("stop")
            status = "stop"
        }

        var indexarr = $(this).parent().attr("id").split("-")
        // console.log(indexarr);
        setStatus(indexarr, status)

    })

    function setStatus(indexarr, status) {
        let data = {}
        data["name"] = indexarr[0]
        data["source"] = indexarr[1]
        data["status"] = status
        let url_current = baseURL + "/setStatus"
        $.ajax({
            type: "POST",
            url: url_current,
            contentType: "application/json",
            dataType: "json",
            data: JSON.stringify(data),
            success: function(res) {
                let status = $(".select-task-with-status .source .cur").attr("class").split("-")[0];
                // console.log(status);
                click_shaixuan(status)
            }
        })
    }
    // 点击任务卡片的编辑按钮
    $(".task_list").on("click", ".edit", function(e) {
        var indexarr = $(this).parent().attr("id").split("-")
        let data = {}
        data["name"] = indexarr[0]
        data["source"] = indexarr[1]
        let url_current = baseURL + "/getDetail"
        $.ajax({
            type: "GET",
            async: false,
            ContentType: 'application/json',
            data: data,
            url: url_current,
            success: function(res) {
                let canshu = res.canshu;
                console.log("--------------------------");
                console.log(canshu);
                console.log(res.source);
                console.log(pingtai[res.source]);
                var source = pingtai[res.source];
                $(".pingtai-list").css("opacity", "0").css("z-index", "0").css("transform", "scale(0.5)");
                $(".shade").css("opacity", "1").css("z-index", "1");
                $(".edit_task").css("transform", "scale(1)");
                $(".box").css("z-index", "0");
                $("." + source + " .form-horizontal .canshu").each(function(i, v) {
                    var id = $(v).attr("id")
                    console.log(id);
                    if (id in canshu) {
                        $(v).val(canshu[id])
                    }
                })
                var decade = res.cycle[0]
                var single = res.cycle[1]
                var unit = res.cycle.substring(2)

                $("." + source + " .form-horizontal #decade").val(decade)
                $("." + source + " .form-horizontal #single").val(single)
                $("." + source + " .form-horizontal #unit").val(unit)
                $("." + source + " #name").val(res.name).attr("readonly", "true");
                $("." + source).css("opacity", "1").css("z-index", "1");
            }
        })

    })

    //点击卡片查看按钮
    $(".task_list").on("click", ".scan", function(e) {
        var indexarr = $(this).parent().attr("id").split("-")
        let data = {}
        data["name"] = indexarr[0]
        data["source"] = indexarr[1]
        open(baseURL + "/" + data.name + "/dataset")
    })

    //点击任务卡片删除按钮
    $(".task_list").on("click", ".delete", function(e) {
        var indexarr = $(this).parent().attr("id").split("-")
        setStatus(indexarr, "delete")
    })

    // 点击取消按钮
    $(".cancel").on("click", function(e) {
        click_cancel()
    })

    //点击确认按钮
    $(".add").on("click", function(e) {
        var id = $(this).attr("id");
        let data = {}
        data['name'] = $("." + id + " #name").val().trim();
        let canshu = {}
        $("." + id + " .form-horizontal .canshu").each(function(i, v) {
            canshu[$(v).attr("id")] = $(v).val()
        })
        data["cycle"] = ""
        $("." + id + " .form-horizontal .cycle").each(function(i, v) {
            data["cycle"] += $(v).val()
        })
        // console.log(data["cycle"]);
        data['source'] = ping_list[id];
        data["canshu"] = canshu;
        data["cyclic"] = 1
        console.log(data);
        let url_current = baseURL + "/addtask"
        $.ajax({
            type: "POST",
            url: url_current,
            contentType: "application/json",
            dataType: "json",
            data: JSON.stringify(data),
            success: function(res) {
                var status = parseInt(res.status)
                if (status == 200) {
                    click_cancel()
                    click_shaixuan("all")
                } else {
                    $(".form-horizontal input").each(function(i, v) {
                        $(v).val("")
                    })
                    $(".form-horizontal textarea").val("")
                }
            }
        })
    })

    function click_shaixuan(status) {
        // console.log("."+status+"-task");
        $("." + status + "-task").addClass("cur").siblings().removeClass("cur")
            // data = { "current": 1 }
        if (status == "all") {
            getdata_list.status = ""
        } else {
            getdata_list.status = status
        }
        getdata_list.current = 1
        resetUI(getdata_list.current)
    }

    // 点击页面上端的筛选按钮，根据运行状态筛选任务
    $(".select-task-with-status .source li").on("click", function(e) {
        var status = $(this).attr("class").split("-")[0]
            // console.log(status);
        click_shaixuan(status)
    })

})